/*****************************************************************************
 * file  : systask.c
 * creat : apleilx
 * note :  除初始化外，禁止该任务及其子程序使用含有阻塞的功能，包括数据存储，USB操作等等
 * data  : 2019/07/02
 *******************************************************************************/
#include "bsp.h"
#include "os_obj.h"
#include "framework.h"

#include "bsp_api.h"
#include "nor_cmd.h"

#include "lut/nand_lut.h"

#include "simp_fat.h"

/*****************************************************************************
 * @brief   const define
 *****************************************************************************/

/*****************************************************************************
 * @brief   var
 *****************************************************************************/
extern nand_lut_type nand_dev;
static char filename[32];
static uint8_t *rd_buff;

/*****************************************************************************
 * @brief   simp_fat hal layer
 * @param   none
 * @return  non
 *****************************************************************************/
simp_fat_err simp_fat_t_read(void *buff, int32_t addr, int32_t len)
{
	nor_read(SWNOR_BASE_SIMP_FAT_TAB + addr, len, buff);

	return SIMP_FAT_OK;
}

simp_fat_err simp_fat_dat_read(void *buff, int32_t addr, int32_t len)
{
	addr += NAND_BASE_SIMP_FAT * nand_dev.page_main_size * nand_dev.page_per_block;
	nand_dev.api.addr_read(addr, len, buff);

	return SIMP_FAT_OK;
}

/*****************************************************************************
 * @brief   simp_fat_test
 * @param   none
 * @return  non
 *****************************************************************************/
DBG_FUN_EXPORT(simp_fat_file_read);
int simp_fat_file_read(int argc, char **argv)
{
	simp_fat_type sfat;
	simp_fat_fil_type sfil;
	simp_fat_err serr;
	int32_t len_back;

	if (argc < 2)
		return 0;

	copy_str(argv[1], filename, sizeof(filename));

	// init fat
	serr = simp_fat_init(&sfat, simp_fat_t_read, simp_fat_dat_read, 1);

	if (serr)
	{
		dbg_print("simp fat init err: %d \n", serr);
		return serr;
	}

	// open file
	serr = simp_fat_open(&sfat, &sfil, filename);

	if (serr)
	{
		dbg_print("simp fat open %s err: %d \n", filename, serr);
		return serr;
	}

	dbg_print("simp open sucess: addr =%08X size=%08X \n", sfil.info.addr_base, sfil.info.size);

	rd_buff = malloc(520);

	// read file data
	do
	{
		serr = simp_fat_read(&sfil, rd_buff, 400, &len_back);

		if (serr)
		{
			dbg_print("simp fat read file %s err: %d \n", filename, serr);
			return serr;
		}

		((char *)(rd_buff))[len_back] = 0;

		dbg_puts((char *)rd_buff);

	} while (len_back == 400);

	// close file
	serr = simp_fat_close(&sfil);

	free(rd_buff);

	return serr;

	return 0;
}
